document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const categoryCards = document.querySelectorAll('.category-card');
    const problemDetailSection = document.getElementById('problemDetailSection');
    const selectedCategoryTitle = document.getElementById('selectedCategoryTitle');
    const backToCategoriesBtn = document.getElementById('backToCategories');
    const analyzeBtn = document.getElementById('analyzeBtn');
    const loadingSection = document.getElementById('loadingSection');
    const analysisResultSection = document.getElementById('analysisResultSection');
    const newAnalysisBtn = document.getElementById('newAnalysisBtn');
    const downloadReportBtn = document.getElementById('downloadReportBtn');
    
    // 问题类别数据
    const categories = {
        'it': {
            title: 'IT类问题',
            rootCauses: ['系统架构不合理', '技术债务过多', '安全措施不足', '缺乏技术文档', '团队技能不足'],
            solutions: [
                { title: '系统架构优化', description: '重新评估系统架构，识别瓶颈并进行优化，提高系统稳定性和性能。' },
                { title: '技术债务清理', description: '制定技术债务清理计划，逐步重构代码，提高系统可维护性。' },
                { title: '安全加固', description: '实施全面的安全评估，加强身份验证、授权和数据加密措施。' },
                { title: '文档完善', description: '建立完整的技术文档体系，包括架构设计、API文档和操作手册。' },
                { title: '团队培训', description: '针对团队技能短板，制定培训计划，提升团队整体技术水平。' }
            ]
        },
        'sales': {
            title: '销售类问题',
            rootCauses: ['市场定位不准确', '销售流程不完善', '客户需求理解不足', '竞争对手分析不足', '销售团队激励不足'],
            solutions: [
                { title: '市场重新定位', description: '深入分析目标市场，重新定位产品和服务，找准市场切入点。' },
                { title: '销售流程优化', description: '梳理销售流程，找出瓶颈环节，优化流程提高转化率。' },
                { title: '客户需求调研', description: '开展客户需求调研，深入了解客户痛点，调整产品和服务策略。' },
                { title: '竞争对手分析', description: '全面分析竞争对手优劣势，制定差异化竞争策略。' },
                { title: '销售团队激励', description: '优化销售团队激励机制，提高团队积极性和凝聚力。' }
            ]
        },
        'finance': {
            title: '财务类问题',
            rootCauses: ['成本控制不严', '现金流管理不善', '财务规划不足', '税务筹划不当', '财务风险预警不足'],
            solutions: [
                { title: '成本精细化管理', description: '实施成本精细化管理，识别并控制主要成本驱动因素。' },
                { title: '现金流优化', description: '优化应收账款管理，加强供应链金融，改善现金流状况。' },
                { title: '财务规划完善', description: '建立长期财务规划机制，提高财务预测准确性。' },
                { title: '税务筹划优化', description: '合理利用税收优惠政策，优化税务筹划方案。' },
                { title: '财务风险管理', description: '建立财务风险预警机制，定期评估财务风险。' }
            ]
        }
    };
    
    let selectedCategory = '';
    
    // 点击问题类别卡片
    categoryCards.forEach(card => {
        card.addEventListener('click', function() {
            selectedCategory = this.dataset.category;
            if (categories[selectedCategory]) {
                selectedCategoryTitle.textContent = categories[selectedCategory].title + '详情';
                problemDetailSection.style.display = 'block';
                window.scrollTo({ top: problemDetailSection.offsetTop - 20, behavior: 'smooth' });
            }
        });
    });
    
    // 返回类别选择
    backToCategoriesBtn.addEventListener('click', function() {
        problemDetailSection.style.display = 'none';
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
    
    // 开始分析
    analyzeBtn.addEventListener('click', function() {
        const problemTitle = document.getElementById('problemTitle').value;
        const problemDescription = document.getElementById('problemDescription').value;
        const problemSeverity = document.getElementById('problemSeverity').value;
        
        // 验证表单
        if (!problemTitle || !problemDescription) {
            alert('请填写问题标题和详细描述');
            return;
        }
        
        // 显示加载中
        problemDetailSection.style.display = 'none';
        loadingSection.style.display = 'block';
        
        // 模拟分析过程（实际应用中可替换为API调用）
        setTimeout(() => {
            // 填充分析结果
            document.getElementById('resultProblemTitle').textContent = problemTitle;
            document.getElementById('resultProblemDescription').textContent = problemDescription;
            document.getElementById('resultProblemCategory').textContent = categories[selectedCategory].title;
            document.getElementById('resultProblemSeverity').textContent = getSeverityText(problemSeverity);
            
            // 生成根本原因分析
            generateRootCauseAnalysis(selectedCategory);
            
            // 生成解决方案建议
            generateSolutions(selectedCategory);
            
            // 生成图表
            generateAnalysisChart(selectedCategory);
            
            // 显示分析结果
            loadingSection.style.display = 'none';
            analysisResultSection.style.display = 'block';
            window.scrollTo({ top: analysisResultSection.offsetTop - 20, behavior: 'smooth' });
        }, 2000);
    });
    
    // 新的分析
    newAnalysisBtn.addEventListener('click', function() {
        analysisResultSection.style.display = 'none';
        document.getElementById('problemForm').reset();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
    
    // 下载报告
    downloadReportBtn.addEventListener('click', function() {
        alert('报告下载功能将在正式版本中提供');
    });
    
    // 生成根本原因分析
    function generateRootCauseAnalysis(category) {
        if (!categories[category]) return;
        
        const rootCauses = categories[category].rootCauses;
        let html = '<ul class="list-group list-group-flush">';
        
        rootCauses.forEach((cause, index) => {
            const probability = 100 - index * 15;
            html += `
                <li class="list-group-item">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>${cause}</div>
                        <div>可能性: ${probability}%</div>
                    </div>
                    <div class="progress mt-2">
                        <div class="progress-bar" role="progressbar" style="width: ${probability}%" 
                            aria-valuenow="${probability}" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </li>
            `;
        });
        
        html += '</ul>';
        document.getElementById('rootCauseContent').innerHTML = html;
    }
    
    // 生成解决方案建议
    function generateSolutions(category) {
        if (!categories[category]) return;
        
        const solutions = categories[category].solutions;
        let html = '';
        
        solutions.forEach((solution, index) => {
            html += `
                <div class="card mb-3">
                    <div class="card-body">
                        <h5 class="card-title">${index + 1}. ${solution.title}</h5>
                        <p class="card-text">${solution.description}</p>
                    </div>
                </div>
            `;
        });
        
        document.getElementById('solutionsContainer').innerHTML = html;
    }
    
    // 生成分析图表
    function generateAnalysisChart(category) {
        if (!categories[category]) return;
        
        const chartContainer = document.getElementById('analysisChart');
        chartContainer.innerHTML = '<canvas id="problemAnalysisChart"></canvas>';
        
        const ctx = document.getElementById('problemAnalysisChart').getContext('2d');
        const rootCauses = categories[category].rootCauses;
        const data = rootCauses.map((_, index) => 100 - index * 15);
        
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: rootCauses,
                datasets: [{
                    label: '问题根本原因分析',
                    data: data,
                    backgroundColor: 'rgba(52, 152, 219, 0.7)',
                    borderColor: 'rgba(52, 152, 219, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '可能性 (%)'
                        }
                    }
                }
            }
        });
    }
    
    // 获取严重程度文本
    function getSeverityText(severity) {
        const severityMap = {
            'low': '轻微',
            'medium': '中等',
            'high': '严重',
            'critical': '危机'
        };
        return severityMap[severity] || '未知';
    }
});